import { ConflictException, Get, Injectable, UseGuards, Request, } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { Role } from 'src/constants/role/role.enum';
import { DateFormatUtil } from 'src/utils/time/time.tools';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserLogin } from './entities/user-login.entity';
import { CreateUserLoginDto } from './dto/create-user-login.dto';






@Injectable()
export class UsersService {

  constructor(
    @InjectRepository(User) private usersRepository: Repository<User>,
    @InjectRepository(UserLogin) private UserLoginRepository: Repository<UserLogin>,
    private jwtService: JwtService,

  ) {

  }

  async register(data, req) {



    console.log("register接收参数：", data)
    //检查验证码
    // const veri_code = data["veri_code"]
    // console.log("验证码为：", veri_code)

    // 检查用户名是否已存在
    const existingUser = await this.usersRepository.findOne({
      where: { email: data["email"] },
    });
    if (existingUser) {
      throw new ConflictException('注册 -- 用户名已存在');
    }
    // 对密码进行哈希
    const salt = bcrypt.genSaltSync(10);
    const hashedPassword = bcrypt.hashSync(data["password"], salt);
    const ip = req.ip || req.headers['x-forwarded-for'];
    const user: CreateUserDto = {
      email: data["email"],
      password: hashedPassword,
      role: Role.User,
      last_ip: ip,
      created_at: DateFormatUtil.getNowDateTime(),
      updated_at: DateFormatUtil.getNowDateTime(),


    };

    // 创建新的用户实例
    const newUser = this.usersRepository.create(user);

    // 保存用户到数据库
    const registeredUser = await this.usersRepository.save(newUser);
    console.log(`创建新用户：${registeredUser.email} 创建时间为：${registeredUser.created_at}`)
    return { message: `用户: ${registeredUser.email} 已成功注册`, code: 201 };
  }
  async login(data, req) {
    const ip = req.ip || req.headers['x-forwarded-for'];
    console.log("上次登录ip：", ip)

    const email = data["email"];
    const password = data["password"];
    const existingUser = await this.usersRepository.findOne({ where: { email } });

    if (!existingUser || !ip) {
      return { message: '用户不存在', code: 400 };
    }




    //密码验证
    // const isPasswordValid = bcrypt.compareSync(password, existingUser.password);
    // if (!isPasswordValid) { 
    //   return { message: '密码错误', code: 401 };
    // }

    const payload = { id: existingUser.id, email: existingUser.email, roles: existingUser.role };
    const access_token = await this.jwtService.signAsync(payload)
    console.log(`用户：${existingUser.email} 登录成功，发放的token为：${access_token}，登录时间为：${DateFormatUtil.getNowDateTime()}`)
    const existingUserLogin = await this.UserLoginRepository.findOne({
      where: { user_id: existingUser.id },
    });
    // console.log(`existingUserLogin: ${JSON.stringify(existingUserLogin)}`)
    if (existingUserLogin) {
      // 创建新的用户实例
      const newUserLogin: CreateUserLoginDto = {
        user_id: existingUser.id,
        user_email: existingUser.email,
        login_ip: ip,
        login_time: DateFormatUtil.getNowDateTime(),
        login_device: "app",
        login_token: access_token,
      }
      

      // 保存用户到数据库
      const LoginUser = await this.UserLoginRepository.update(existingUser.id,newUserLogin);
      // console.log(`创建用户新登录：${LoginUser.user_id} 创建时间为：${LoginUser.login_time}`)

    }
    else {
      const newUserLogin: CreateUserLoginDto = {
        user_id: existingUser.id,
        user_email: existingUser.email,
        login_ip: ip,
        login_time: DateFormatUtil.getNowDateTime(),
        login_device: "app",
        login_token: access_token,
      }

      // 创建新的用户实例
      const newUserLoginLog = this.UserLoginRepository.create(newUserLogin);
      // 保存用户到数据库
       await this.UserLoginRepository.save(newUserLoginLog);
      console.log(`更新用户：成功`)

    }

    return { message: '登录成功', token: access_token, code: 200 };
  }



  async getProfile(userID: number) {
    const user = await this.usersRepository.findOne({
      where: { id: Number(userID) },
    });
    const data = {
      email: user.email,
      role: user.role,
      phone: user.phone,
      nickname: user.nickname,
      gender: user.gender,
      steamID: user.steamID
    }


    return { mesage: `获取 ${user.id} 资料成功`, data: data, code: 200 }
  }
  async updateProfile(req) {
    const data = req.body
    const newData: UpdateUserDto = {
      phone: data["phone"],
      nickname: data["nickname"],
      gender: data["gender"],
      steamID: data["steamID"],
      updated_at: DateFormatUtil.getNowDateTime(),
    }
    let user = await this.usersRepository.findOne({
      where: { id: req.user.id },
    });
    if (user) {
      // 将接收到的数据对象直接赋值给用户实体，然后使用 save 进行更新
      user.phone = newData.phone;
      user.nickname = newData.nickname;
      user.gender = newData.gender;
      user.steamID = newData.steamID;

      // 保存更新后的用户到数据库
      await this.usersRepository.save(user);
      console.log(`更新 ${user.id} 资料成功`);
      return { message: `更新 ${user.id} 资料成功`, code: 200 };
    } else {
      return { message: `用户 ${user.id} 不存在`, code: 400 };
    }

  }
  async verifyToken(token:string,userID):Promise<boolean>{
   const user =  await this.UserLoginRepository.findOne({
      where: { user_id: userID },
    })
    if(user.login_token == token){
      console.log("token 验证成功")
      return true
    }else{
      console.log("token 验证失败")
      return false
    }
  }


}
